package com.qf.servlet;

import com.qf.constant.MyConstant;
import com.qf.convert.MyConvert;
import com.qf.pojo.User;
import com.qf.service.UserService;
import com.qf.service.impl.UserServiceImpl;
import com.qf.utils.MD5Utils;
import com.qf.utils.UUIDUtils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

/**
 * 前台用户模块的控制器
 */
@WebServlet("/user")
public class UserServlet extends BaseServlet {


     /**
     * 注册前先校验用户名的方法
     * @param request 请求对象
     * @param response 响应对象
     */
    public void checkUser(HttpServletRequest request,HttpServletResponse response) throws IOException {
       // System.out.println("进入check方法了....");
        //接收参数${pageContext.request.contextPath}/check?username="+username+""
        String username = request.getParameter("username");
        //调用前台用户业务接口
        UserService userService = new UserServiceImpl() ;
        boolean flag = userService.checkUser(username);
        if(flag){
            //可以注册
            response.getWriter().write("1");
        }else{
            //不能注册
            response.getWriter().write("0");
        }

    }


    /**
     * 跳转注册页面的方法
     * @param request
     * @param response
     */
    public void registerUI(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {

        //请求转发到"/jsp/register.jsp"
        request.getRequestDispatcher("/jsp/register.jsp").forward(request,response);

    }

    /**
     * 注册用户方法
     * @param request 请求对象
     * @param response 响应对象
     * @throws ServletException
     * @throws IOException
     */
    public void reigster(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {



        //获取前台用户输入的验证码的内容
        String userCode = request.getParameter("userCode");
        //从服务器端获取存储的验证码---->HttpSession域
        HttpSession session = request.getSession();//这里面绑定一个属性以及内容的内容:验证码
        //"CHECKCODE_SERVER"属性绑定的4个验证码
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");


        //验证码是一次性验证码
        session.removeAttribute("CHECKCODE_SERVER");
        //如果不一致,那么错误提示
        //用户输入的内容为空或者内容不匹配
        if(userCode==null || !userCode.equalsIgnoreCase(checkcode_server)){
            //错误提示
            request.setAttribute("msg","验证码输入错误") ;
            //请求转发到
            request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response) ;
        }


        //验证码如果一致
        //获取用户其他的 参数数据
        Map<String, String[]> parameterMap = request.getParameterMap();
        //封装User对象
        User user = new User();

        //封装用户之前,处理出生日期
        ConvertUtils.register(new MyConvert(), Date.class);
        try {
            BeanUtils.populate(user,parameterMap);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

        //用户的其他数据:
        //uid 用户编号:通过jdk工具类 UUID生成
        user.setUid(UUIDUtils.getId());
        //密码:需要加密
        String password = request.getParameter("password");
        user.setPassword(MD5Utils.md5(password));
        //激活码 也是UUID工具产生的
        user.setCode(UUIDUtils.getCode());
        System.out.println(user);

        //调用业务接口
        UserService userService = new UserServiceImpl();
        userService.registerUser(user) ;

        //给reuqest域中添加数据
        request.setAttribute("msg","恭喜您,注册成功,请激活邮箱");
        request.getRequestDispatcher("/jsp/msg.jsp").forward(request,response);



    }


    /**
     * 注册的通过邮件激活用户
     * @param request
     * @param response
     */
    public void active(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        //http://localhost:8080/Maven_Project_02_war/user?methodName=active&code=A70255E0137C450289533A75A035C663

        //获取参数
        String code = request.getParameter("code");
        //System.out.println(code) ;

        ///调用业务接口
        UserService userService = new UserServiceImpl();
        User user = userService.getUserByCode(code);
        if (user != null) {
            //找到了
            request.setAttribute("msg", "恭喜您,用户激活成功,<a href='/Maven_Project_02_war/jsp/login.jsp'>请登录</a>");
            request.getRequestDispatcher("/jsp/msg.jsp").forward(request, response);
        } else {
            //错误提示
            request.setAttribute("msg", "对不起,用户激活失败,请重新激活");
            request.getRequestDispatcher("/jsp/msg.jsp").forward(request, response);
        }
    }

    /**
     * 跳转登录页面的方法
     * @param request 请求对象
     * @param response 响应对象
     */
    public void loginUI(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
    }



    /**
     * 前台用户登录功能
     * @param request 响应对象
     * @param response 响应对象
     */

    public void login(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //1)校验验证码
        //获取前台用户输入的验证码
        String userCode = request.getParameter("userCode");
        //获取服务器端存储的验证码
        HttpSession session = request.getSession();
        String checkcode_server = (String) session.getAttribute("CHECKCODE_SERVER");

        //验证码一次性验证码
        session.removeAttribute("CHECKCODE_SERVER");
        if(userCode==null || !userCode.equalsIgnoreCase(checkcode_server)){
            //错误提示
            request.setAttribute("msg","验证码输入错误") ;
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }

        //2)验证码一致
        //接收的用户名
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username+"----"+password);
        //密码加密
        password = MD5Utils.md5(password) ;
        System.out.println(password);

        //3)调用业务接口 去查询用户 根据用户名和密码
        UserService userService = new UserServiceImpl() ;
        User user = userService.getUserByUsernameAndPassword(username, password);

        //如果用户是空的
        if(user ==null){
            //错误提示
            request.setAttribute("msg","用户名或者密码输入错误") ;
            //请求转发到login.jsp
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response);
        }
        //如果用户存在,但是用户的激活状态是0,未激活
        if(user.getState()== MyConstant.USER_ACTIVE_STATE){
            //错误提示
            request.setAttribute("msg","用户未激活,<a href='/Maven_Project_02_war/userActive?code="+user.getCode()+"'>请激活</a>");
            request.getRequestDispatcher("/jsp/login.jsp").forward(request,response) ;
        }

        //如果用户存在,用户的激活状态1
        //User对象存储到Session中
        session.setAttribute("user",user) ;


        //自动登录 ,判断用户是否勾选了自动登录
        //获取前台自动能录的参数name="autouser"
        String autouser = request.getParameter("autouser");
        if(!"AutoUser".equals(autouser)){
            //没有勾选 ,给浏览器不存储cookie
            //创建Cookie
            Cookie cookie = new Cookie("autoUser","") ;
            //有效期:0 删除cookie
            cookie.setMaxAge(0);
            //服务器携带cookie
            response.addCookie(cookie);

        }else{
                //勾选了
            //存储的cookie的内容
            String content = user.getUsername()+"="+user.getPassword() ;
            //jdk提供的加密工具  URLEncoder public static String encode(String s,String enc)
            content = URLEncoder.encode(content,"utf-8") ;
            //存储Cookie
            Cookie cookie = new Cookie("autoUser",content) ;

            //设置有效期 1个月
            cookie.setMaxAge(60*60*24*30) ;
            //服务器将cookie内容携带浏览器
            response.addCookie(cookie);
        }


        //重定向到首页
        response.sendRedirect(request.getContextPath()+"/");
    }


    /**
     * 用户退出
     * @param request 请求对象
     * @param response  响应对象
     */
    public void logout(HttpServletRequest request,HttpServletResponse response) throws IOException {

        //通过请求对象获取session
        HttpSession session = request.getSession();

        //将session中存储的"user"属性的内容清除掉
        //public void removeAttribute(String name)
        session.removeAttribute("user") ;

        //重定向到首页
        response.sendRedirect(request.getContextPath()+"/");

    }



}
